<template>
  <div class="flex flex-col items-center w-screen h-screen">
    <div
      class="flex flex-col w-[1015px] h-[456px] rounded-lg bg-gradient-to-br from-[#FFE8EA] to-[#EDF2FB] items-center p-5"
    >
      <div class="flex w-[720px] h-[52px] justify-center text-[15px]">
        未来30天将有16天下雨，有1天温度超过35°，最高温36°（09月05日），最低温17°（09月27日）。
      </div>
      <div class="flex flex-col flex-wrap w-[960px] h-[334px]">
        <div class="flex flex-wrap w-[735px] h-[333px]">
          <div class="flex flex-wrap w-[735px] h-[16px] justify-around">
            <p>日</p>
            <p>一</p>
            <p>二</p>
            <p>三</p>
            <p>四</p>
            <p>五</p>
            <p>六</p>
          </div>
          <div class="flex">
            <div class="flex flex-wrap w-[735px] h-[306px] py-2">
              <div
                v-for="n in blankDaysCount"
                :key="'blank-' + n"
                class="flex w-[101px] h-[57px] m-[2px] rounded opacity-50"
              ></div>
              <div
                class="flex flex-col w-[101px] h-[57px] m-[2px] rounded-lg cursor-pointer"
                :class="{
                  'bg-white hover:bg-red-200': selectedDate
                    ? item.fxDate !== selectedDate.fxDate
                    : false,
                  '!bg-red-200 border-2 border-red-500':
                    selectedDate && item.fxDate === selectedDate.fxDate,
                }"
                v-for="item in weatherlist"
                :key="item.fxDate"
                @click="selectedDate = item"
              >
                <div class="flex w-[99px] h-[22px] justify-between p-1">
                  <span class="text-[#00000080]">{{
                    item?.fxDate?.slice(-2)
                  }}</span>
                  <i v-bind:class="`qi-${item.iconDay}`"></i>
                </div>
                <div
                  class="flex justify-center items-center w-[99px] h-[32px] text-[#0000000]"
                >
                  {{ item.tempMax }} °~ {{ item.tempMin }}°
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="flex flex-col w-[220px] h-[330px]">
          <div class="flex w-[220px] h-[25px] justify-center items-center">
            <p class="mx-2">高温</p>
            <p class="mx-2">低温</p>
          </div>

          <div class="flex flex-col w-[220px] h-[304px] bg-white rounded-lg">
            <div class="flex items-center w-[220px] h-[46px] px-3">
              <p>{{ selectedDate.fxDate }}</p>
            </div>
            <div class="w-[220px] h-[1.5px] bg-slate-100"></div>
            <div class="flex flex-col items-center w-[220px] h-[240px]">
              <div class="flex items-center w-[200px] h-[62px]">
                <div class="w-[128px] h-[51px]">
                  <p class="text-xl">
                    {{ selectedDate.tempMax }} °~ {{ selectedDate.tempMin }}°
                  </p>
                  <p>{{ selectedDate.textDay }}</p>
                </div>
                <div class="flex justify-center w-[61px]">
                  <i
                    v-bind:class="`qi-${selectedDate.iconDay} text-[40px]`"
                  ></i>
                </div>
              </div>
              <div class="flex justify-between w-[200px] h-[40px] mt-2">
                <div class="w-[87px] h-[40px]">
                  <p>{{ selectedDate.windScaleDay }}级</p>
                  <p class="text-[#00000080]">{{ selectedDate.windDirDay }}</p>
                </div>
                <div class="w-[87px] h-[40px]">
                  <p>{{ selectedDate.precip }}mm</p>
                  <p class="text-[#00000080]">降水量</p>
                </div>
              </div>
              <div class="flex justify-between w-[200px] h-[40px] mt-4">
                <div class="w-[87px] h-[40px]">
                  <p>{{ selectedDate.windScaleDay }}</p>
                  <p class="text-[#00000080]">紫外线</p>
                </div>
                <div class="w-[87px] h-[40px]">
                  <p>{{ selectedDate.humidity }}%</p>
                  <p class="text-[#00000080]">空气湿度</p>
                </div>
              </div>
              <div class="flex justify-between w-[200px] h-[40px] mt-4">
                <div class="w-[87px] h-[40px]">
                  <p>{{ selectedDate.sunrise }}</p>
                  <p class="text-[#00000080]">日出</p>
                </div>
                <div class="w-[87px] h-[40px]">
                  <p>{{ selectedDate.sunset }}</p>
                  <p class="text-[#00000080]">日落</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="flex w-[1015px] h-[1200px]">
      <div class="flex justify-center mt-4">
        <div
          class="rounded-lg shadow-md p-4 border"
          style="width: 640px; height: 418px"
        >
          <div id="temperature-chart" style="width: 100%; height: 100%"></div>
        </div>
        <div
          class="flex flex-col items-center w-[353px] ml-5 bg-[#F7F8F9] rounded-lg"
        >
          <div class="text-[22px] mt-5">附近城市</div>

          <div
            class="flex items-center w-[310px] h-[45px] mt-3 bg-slate-100 rounded-lg cursor-pointer"
          >
            <p class="flex text-[20px] p-2.5">武汉市</p>
            <i
              v-bind:class="`qi-${weatherlist[0].iconDay} text-[40px]`"
              class="pl-[85px]"
            ></i>
            <div class="text-[#000000] text-[20px] pl-[20px]">
              {{ weatherlist[0].tempMax }}°~{{ weatherlist[0].tempMin }}°
            </div>
          </div>
          <div v-for="item in storedWeatherData">
            <div
              class="flex items-center w-[310px] h-[45px] mt-3 bg-slate-100 rounded-lg cursor-pointer"
            >
              <p class="flex text-[20px] p-2.5">{{ item.name }}</p>
              <i
                v-bind:class="`qi-${item.iconDay} text-[40px]`"
                class="pl-[85px]"
              ></i>
              <div class="text-[#000000] text-[20px] pl-[20px]">
                {{ item.maxTemp }}°~{{ item.minTemp }}°
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import axios from "axios";
import { ref, onMounted, nextTick } from "vue";
import * as echarts from "echarts"; // 必须引入ECharts

var blankDaysCount = ref(0);
var weatherlist = ref([]);
var selectedDate = ref(null);
var myChart = ref(null); //

// 附近城市的location ID
const cityIds = [
  "101200501", // 黄冈市
  "101200301", // 鄂州市
  "101200401", // 孝感市
  "101200601", // 黄石市
  "101200701", // 咸宁市
  "101201301", // 随州市
  "101251001", // 岳阳市
  "101240201", // 九江市
  "101180601", // 信阳市
];

// 城市ID与名称的映射
const cityNames = {
  101200501: "黄冈市",
  101200301: "鄂州市",
  101200401: "孝感市",
  101200601: "黄石市",
  101200701: "咸宁市",
  101201301: "随州市",
  101251001: "岳阳市",
  101240201: "九江市",
  101180601: "信阳市",
};

// 存储所有城市天气数据的对象
const storedWeatherData = {};

// 遍历所有城市并获取天气数据
cityIds.forEach((cityId) => {
  axios
    .get(
      `https://kp2k5n7bag.re.qweatherapi.com/v7/weather/30d?location=${cityId}&key=b050a8442736451384c608f4ab61b616`
      // {
      //   headers: {
      //     Authorization:
      //       "Bearer eyJhbGciOiJFZERTQSIsImtpZCI6Iks0NUY1R0pRTVAifQ.eyJzdWIiOiI0OVRORjZRRUpWIiwiaWF0IjoxNzU3NTcwODgyLCJleHAiOjE3NTc2NTcyODJ9.tgyV0Ric5fuBRXxJjsF-p9k9qafhmprj7L-49FibuLDxj6iWMUh4VAjYrC7UJ-kFpo8kawH-2OLa20SI1h-ICQ",
      //   },
      // }
    )
    .then(function (response) {
      // 获取当天天气数据
      const todayWeather = response.data.daily[0];

      // 存储数据
      storedWeatherData[cityId] = {
        name: cityNames[cityId],
        date: todayWeather.fxDate,
        dayWeather: todayWeather.textDay,
        nightWeather: todayWeather.textNight,
        maxTemp: todayWeather.tempMax,
        minTemp: todayWeather.tempMin,
        iconDay: todayWeather.iconDay,
      };

      // 检查是否所有城市数据都已获取
      if (Object.keys(storedWeatherData).length === cityIds.length) {
        console.log("所有城市数据已获取并存储完成!");
        console.log("存储的数据对象:", storedWeatherData);
      }
    })
    .catch(function (error) {
      console.error(`获取${cityNames[cityId]}天气数据失败:`, error.message);
    });
});
// 获取天气数据
axios
  .get(
    "https://kp2k5n7bag.re.qweatherapi.com/v7/weather/30d?location=101200111&key=b050a8442736451384c608f4ab61b616"
    // {
    //   headers: {
    //     Authorization:
    //       "Bearer eyJhbGciOiJFZERTQSIsImtpZCI6Iks0NUY1R0pRTVAifQ.eyJzdWIiOiI0OVRORjZRRUpWIiwiaWF0IjoxNzU3NTcwODgyLCJleHAiOjE3NTc2NTcyODJ9.tgyV0Ric5fuBRXxJjsF-p9k9qafhmprj7L-49FibuLDxj6iWMUh4VAjYrC7UJ-kFpo8kawH-2OLa20SI1h-ICQ",
    //   },
    // }
  )
  .then(function (res) {
    console.log(res);
    weatherlist.value = res.data.daily;
    selectedDate.value = res.data.daily[0];
    blankDaysCount.value = new Date(res.data.daily[0].fxDate).getDay();

    // 数据加载完成后，初始化图表
    nextTick(() => {
      initChart();
    });
  })
  .catch(function (err) {
    console.log(err);
  });

// 初始化图表的函数
const initChart = () => {
  const chartDom = document.getElementById("temperature-chart");
  if (!chartDom) return;

  // 初始化ECharts实例
  myChart.value = echarts.init(chartDom);

  // 准备图表数据 - 注意要用 .value
  const dates = weatherlist.value.map(
    (item) => item.fxDate?.substring(5) || ""
  );
  const tempMax = weatherlist.value.map((item) => parseInt(item.tempMax) || 0);
  const tempMin = weatherlist.value.map((item) => parseInt(item.tempMin) || 0);

  // 配置项
  const option = {
    title: {
      text: "未来30天最高/最低温度",
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#ddd",
      textStyle: {
        color: "#333",
      },
    },
    legend: {
      data: ["最高温度", "最低温度"],
      bottom: 10,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: dates,
      axisLabel: {
        rotate: 30,
        interval: 0,
      },
    },
    yAxis: {
      type: "value",
      name: "温度 (°C)",
      nameTextStyle: {
        padding: [0, 30, 0, 0],
      },
    },
    series: [
      {
        name: "最高温度",
        type: "line",
        data: tempMax,
        smooth: true,
        symbol: "circle",
        symbolSize: 6,
        itemStyle: {
          color: "#ff6b6b", // 更鲜明的红色
        },
        lineStyle: {
          width: 2,
        },
      },
      {
        name: "最低温度",
        type: "line",
        data: tempMin,
        smooth: true,
        symbol: "circle",
        symbolSize: 6,
        itemStyle: {
          color: "#4dabf7", // 更鲜明的蓝色
        },
        lineStyle: {
          width: 2,
        },
      },
    ],
  };

  // 渲染图表
  myChart.value.setOption(option);

  // 监听窗口大小变化，自动调整图表大小
  window.addEventListener("resize", () => {
    if (myChart.value) {
      myChart.value.resize();
    }
  });
};

// 在组件挂载后初始化图表
onMounted(() => {
  nextTick(() => {
    initChart();
  });
});
</script>
